//
//  PersonDetailView.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/25.
//

import UIKit
import ViewAnimator

class PersonDetailView: UITableViewController {
    
    var cancelSelectedDelegate: CancelSelectedDelegate?
    private let tableCellReuseIdentifier = "PersonDetailCell"
    private let detailView = DetailViewController()
    private var currentIndex: IndexPath!
    private var setion : [String] = ["修改密码","修改资料","注销账号"]
    private var stateView : DetailStateView!
    private var clearView : UIView!
    
    //MARK:Life cycle
    override func viewWillAppear(_ animated: Bool) {
        commonInit()
        tableView.reloadData()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        cancelSelectedDelegate?.cancelSelected()
        if stateView != nil, clearView != nil{
            removeStateView()
        }
    }
    
    private func commonInit(){
        let nib = UINib(nibName: tableCellReuseIdentifier, bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: String(describing: PersonDetailCell.self))
        self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        if Module == .set{
            self.tableView.rowHeight = 46
        }else{
            self.tableView.rowHeight = 100
        }
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        var numForCell : Int = 0
        if let user = userSelf{
            switch  Module{
            case .myBorrow:
                numForCell = user.borrow.count
            case .myCollect:
                numForCell = user.collection.count
            case .myShare:
                numForCell = user.share.count
            case .set:
                numForCell = setion.count
            default:
                break
            }
        }
        return numForCell
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: tableCellReuseIdentifier, for: indexPath) as! PersonDetailCell
        if let user = userSelf{
            cell.frame = tableView.frame
            switch Module {
            case .myBorrow:
                if let count = userSelf?.borrow.count, count > 0, let faceImage = user.borrow[indexPath.row].face{
                    cell.bookFace.image = faceImage
                    cell.label.text = "审核状态：正在申请"
                }
            case .myCollect:
                if userSelf?.collection.isEmpty == false{
                    if let faceImage = userSelf?.collection[indexPath.row].face{
                     cell.bookFace.image = faceImage
                    }
                }
                if let time = userSelf?.collection[indexPath.row].collectedTime{
                    cell.label.text = "收藏时间：\(time)"
                }
            case .myShare:
                if userSelf?.share.isEmpty == false{
                    if let faceImage = userSelf?.share[indexPath.row].face{
                        cell.bookFace.image = faceImage
                    }
                    cell.label.text = "审核状态：正在审核"
                }
            case .set:
                cell.label.text = setion[indexPath.row]
            default:
                break
            }
        }
        return cell
    }
    
    //MARK:DidSelect
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentIndex = indexPath
        switch Module {
        case .myCollect:
            showDetailView(books: userSelf?.collection, indexPath: indexPath)
        case .myBorrow:
            showDetailView(books: userSelf?.borrow, indexPath: indexPath)
        case .myShare:
            presentDetailStateView(indexPath: indexPath)
        default:
            break
        }
        
    }
    
    private func showDetailView(books:[Book]?,indexPath:IndexPath){
        if books != nil{
            currentBook = books![indexPath.row]
            detailView.cancelSelectedDelegate = self
            present(detailView, animated: true, completion: nil)
        }
    }
    
    private func presentDetailStateView(indexPath:IndexPath){
        clearView = UIView(frame: self.view.bounds)
        clearView.backgroundColor = .gray
        clearView.alpha = 0.2
        clearView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissDetailStateView(tap:))))
        currentBook = userSelf?.share[indexPath.row]
        stateView = DetailStateView(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 400)))
        stateView.center = self.view.center
        self.view.addSubview(clearView)
        self.view.addSubview(stateView)
        let actionFrom = AnimationType.from(direction: .bottom, offset: 400)
        stateView.animate(animations: [actionFrom])
    }
    
    @objc func dismissDetailStateView(tap:UIGestureRecognizer){
        switch tap.state {
        case .ended:
            removeStateView()
        default:
            break
        }
    }
    
    private func removeStateView(){
        stateView.removeFromSuperview()
        clearView.removeFromSuperview()
        UIView.animate(withDuration: 0.2) { [self] in
            tableView.cellForRow(at: currentIndex)?.isSelected = false
        }
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            switch Module {
            case .myCollect:
                if let book = userSelf?.collection[indexPath.row]{
                    book.state.isCollected = false
                    userSelf?.collection.remove(at: indexPath.row)
                    LC.userHandleCollection(book: book, isCollect: false)
                }
            case .myBorrow:
                if let book = userSelf?.borrow[indexPath.row]{
                    book.state.isBorrowed = false
                    userSelf?.borrow.remove(at: indexPath.row)
                    LC.userHandleBorrow(book: book, isBorrow: false)
                }
            case .myShare:
                userSelf?.share.remove(at: indexPath.row)
            default:
                break
            }
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            
        }    
    }
    
}
//MARK:CancelSelectedDelegate
extension PersonDetailView: CancelSelectedDelegate{
    func cancelSelected() {
        UIView.animate(withDuration: 0.2) { [self] in
            tableView.cellForRow(at: currentIndex)?.isSelected = false
        }
    }
    
}
